package com.example.demo.thread;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

public class Demo11 {


    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        List<Integer> intList = Collections.synchronizedList(list);
        List<Integer> ids = Arrays.asList(1, 2, 3);
        CountDownLatch countDownLatch = new CountDownLatch(ids.size());
        ExecutorService threadPollExecutor = Executors.newFixedThreadPool(3);
        for (Integer id : ids) {
            threadPollExecutor.execute(() -> {
                try {
                    for (int i = 0; i <= id; i++) {
                        intList.add(i);
                    }
                    TimeUnit.SECONDS.sleep(10);
                } catch (Exception e) {
                    System.out.println("execute exception ...");
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            // 此处await可以加上过期时间，防止意外情况线程中的countDown并没执行,导致线程池被打满
            countDownLatch.await();
        } catch (InterruptedException ie) {
            System.out.println("async get department has been interrupt");
            // 设置线程的中断标志，发生中断捕获后要让更高级别的中断处理程序会注意到它并且可以正确处理它
            Thread.currentThread().interrupt();
        }
        System.out.println(intList);
    }
}
